
//
//  LinkedList_subscript.swift
//  SwiftyDSA
//
//  Created by Archer on 2018/8/8.
//  Copyright © 2018年 Archer. All rights reserved.
//

import Foundation

extension LinkedList {
    /// It's not efficent
    public subscript(index: Int) -> Element {
        set {
            // precondition保证了不会迭代到_trailer
            precondition(index >= 0 && index < _size, "\(index)越界")
            var nd = _header.successor
            for _ in 0..<index {
                nd = nd?.successor
            }
            nd?.value = newValue
        }
        get {
            precondition(index >= 0 && index < _size, "\(index)越界")
            var nd = _header.successor
            for _ in 0..<index {
                nd = nd?.successor
            }
            // 只有_header/_trailer才是Element?
            // 对于其他节点是Element
            // 也就是说如果插入的是nil
            // nd.value 就是 Element??
            // force-unwrap是安全的(得到Element?)
            return (nd?.value)!
        }
    }
}
